import React, { PureComponent } from 'react';
// 引入样式
import './scss/short.scss'
// 发送axios
import Axios from 'axios';
// 引入接口
import { webSite } from '../../website'
// 引入样式
import { message, Button, Input } from 'antd';
// 引入点击复制到粘贴板的办法
import copy from 'copy-to-clipboard';
let { TextArea } = Input
export default class Short extends PureComponent {
  constructor() {
    super()
    this.state = {
      textArea: '',
      istextArea: ''
    }
  }
  // input输入时的回调函数
  handleInput = ({ target }) => {
    let { name, value } = target
    // 设置input和state同步
    this.setState({
      [name]: value
    })
  }
  // 转换网址
  shortBtn = () => {
    let { textArea } = this.state;
    if (!textArea) {
      message.info({ content: '必须有内容', className: 'bulletChatMessage' });
      return;
    }
    // 网址发送给后台
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/getShort", { url: textArea }).then(err => {
      if (err.data.code === 'S0001') {
        // 把服务器转换的url地址发送给前端
        this.setState({
          istextArea: `${webSite}:3003/url/${err.data.url}`
        })
      }
    }).catch(() => {
      message.error({ content: '请检查您的网络连接', className: 'bulletChatMessage' });
    })
  }
  // 首页文字点击
  BtnCopy = () => {
    let { istextArea } = this.state
    if (istextArea) {
      if (copy(istextArea)) {
        message.success({ content: '短网址复制成功', className: 'bulletChatMessage' });
      } else {
        message.error({ content: '您的设备不支持自动复制', className: 'bulletChatMessage' });
      }
    }
  }
  // 清空网址
  deleteInput = () => {
    this.setState({
      textArea: '',
      istextArea: ''
    })
  }
  render () {
    let { istextArea, textArea } = this.state;
    return (
      <div className='short'>
        <h3>输入要转换的长网址</h3>
        <div className='short_body'>
          <TextArea rows={6} placeholder='输入长网址' value={textArea} name='textArea' onChange={this.handleInput} maxLength='200' className='short_TextArea' />
          <img src={require('../translate/image/deleteinput.png')} alt="删除" className='shortCopy' onClick={this.deleteInput} />
        </div>
        <Button onClick={this.shortBtn} className='short_button' type='text'>生成短网址</Button>
        <div className='short_body'>
          <TextArea rows={6} placeholder='这里是转换的短网址' value={istextArea} name='istextArea' onChange={this.handleInput} maxLength='100' className='short_TextArea' />
          <img src={require('../translate/image/copylianjie.png')} alt="copy" onClick={this.BtnCopy} className='shortCopy' />
        </div>
      </div>
    )
  }
}